/*============================================================================
 * Copyright 2009 VMware Inc.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at: http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 ============================================================================*/

package com.vmware.vcloud;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Calendar;

import javax.xml.bind.DatatypeConverter;

import org.dom4j.Element;

import com.vmware.vcloud.data.TaskStatus;
import com.vmware.vcloud.rest.RestClient;

/**
 * @author Steve Jin (sjin@vmware.com)
 */

public class Task extends VCloudObject 
{
	Calendar startTime;
	Calendar endTime;
	TaskStatus status;
	
	VCloudObject owner;
	VCloudObject result; 
	
	public Task(RestClient rc, String urlPath) throws MalformedURLException
	{
		super(rc, urlPath);
	}
	
	protected void parse() throws MalformedURLException
	{
		startTime = DatatypeConverter.parseTime(root.attributeValue("startTime"));
		String etStr = root.attributeValue("endTime");
		if(etStr!=null) //endTime attribute can be NULL
		{
			endTime = DatatypeConverter.parseTime(etStr);
		}
		status = TaskStatus.valueOf(root.attributeValue("status"));
		
		Element oe = root.element("Owner");
		//TODO it is not necessary to be VDC, or VApp 
		owner = new VDC(rc, oe.attributeValue("href"), oe.attributeValue("name"));
		
		Element re = root.element("Result");
		if(re!=null) //result element can be NULL
		{
			owner = new VApp(rc, re.attributeValue("href"), re.attributeValue("name"));
		}
	}
	
	public TaskStatus getStatus() throws IOException
	{
		refresh();
		return status;
	}

	public TaskStatus waitFor(int intervalInMillSecond) throws IOException, InterruptedException
	{
		for(;;)
		{
			Thread.sleep(intervalInMillSecond);
			TaskStatus status = getStatus();
			
			if(status == TaskStatus.queued || status == TaskStatus.running)
			{
				continue;
			}
			else
			{
				return status;
			}
		}
	}
	
	//TODO: it seems impossible to cancel a task
	public void cancel()
	{
	}
	
}
